//
//  DishThumbWrapperView.m
//  XRmenu
//
//  Created by loufq on 11-3-21.
//  Copyright 2011 E0571. All rights reserved.
//

#import "DishThumbWrapperView.h"

@interface DishThumbWrapperView(Private)
-(void)loadThumbView;
-(void)transitionWithDirection:(NSString*)aDirection type:(NSString*)aType;
-(CABasicAnimation*)scaleAnimationWithFromVal:(float_t)aFromVal toVal:(float_t)aToVal duration:(float_t)aDuration;
-(CABasicAnimation*)positionAnimationWithFromVal:(CGPoint)aFromPoint toVal:(CGPoint)aToPoint duration:(float_t)aDuration;

-(void)playAnimationWithThumb:(DishThumbView*)aView type:(NSInteger)aType;


-(void)perSetTableView;
@end

@implementation DishThumbWrapperView
@synthesize datasource;
@synthesize delegate;
@synthesize mNavView;
@synthesize displayModel;
@synthesize specDishId;
@synthesize currentDishThumbView;

#define kDefaultThumbWrapperSize (CGSizeMake(220,211))
#define kDefaultThumbSize CGSizeMake(208,156)
#define kDefaultThumbWrapperMarginSize CGSizeMake(10,3)
#define kTagDishAlbumNavView 402
#define kTagOperView 1000
#define kTagAnimationLayerName @"addDishLayer"
#define kTagFilpView 401

-(void)dealloc
{
	removeNObserver(kMessage_Album_CloseOperView);
    self.currentDishThumbView = nil;
	self.specDishId =nil;
	self.mNavView=nil;
	self.datasource = nil;
	self.delegate = nil;
	[super dealloc];
}

#define kTagSortViewBegin 801

-(id)initWithTarget:(id)aTarget position:(CGPoint)aPosition style:(NSInteger)aDishDisplayModel
{
	if ((self = [super init])){
		
		addNObserver(@selector(closeOperView),kMessage_Album_CloseOperView);
		currentPageIndex = 0;
		self.frame = CGRectMake(aPosition.x, aPosition.y, 0, 0); 
		self.delegate = aTarget;
		self.datasource = aTarget;  
		thumbWrapperSize = kDefaultThumbWrapperSize;
		thumbImageSize = kDefaultThumbSize;
		thumbMargin =kDefaultThumbWrapperMarginSize;
		displayModel = aDishDisplayModel;
		if ([aTarget respondsToSelector:@selector(dishThumbWrapperSize)]) {
			thumbWrapperSize = [self.datasource dishThumbWrapperSize]; 
		}
		if ([aTarget respondsToSelector:@selector(dishThumbImageSize)]) {
			thumbImageSize =[self.datasource dishThumbImageSize];
		}
		if ([aTarget respondsToSelector:@selector(dishThumbMargin)]) {
			thumbMargin = [self.datasource dishThumbMargin];
		}
		[self add1fingerLeftSwipe];
		[self add1fingerRightSwipe];
		[self add1fingerTap];
 
 
		//导航条
		NSDictionary* aDic = [self findNode:APPSESSION.allconfig withKey:@"DishAlbumNavView"];
		DishAlbumNavView* navView =[[DishAlbumNavView alloc] initWithConfig:aDic];
		navView.frame = CGRectMake(1, self.frame.size.height-29, self.frame.size.width , 30);
		navView.tag=kTagDishAlbumNavView;
		navView.delegate=self;
		self.mNavView = navView;
		[self addSubview:navView];
		[navView release]; 
		//初始化
		[self perSetTableView];
		
		
	}
	return self;
}

-(void)closeOperView
{
	if ([self viewWithTag:kTagOperView]) {
		[[self viewWithTag:kTagOperView] removeFromSuperview];
	}
	
}
- (void)handleTapFrom:(UITapGestureRecognizer *)recognizer {
	CGPoint location = [recognizer locationInView:self];
	 
	CGRect f = CGRectMake(0, 0, 155, 34);
 
	if (CGRectContainsPoint(f, location)) {
		postN(kMessage_Main_Clean);
		return;
	}
}

//刷新点单数量
-(void)freshInfoWithProduct:(Product*)aProduct
{
	
	//在这一页找到对应Product 修改点单数量
	int delIndex = kTagSortViewBegin;
	DishThumbView* obj = nil;
	while ((obj = (DishThumbView *)[self viewWithTag:delIndex])) {
	
		NSInteger iCount =[XRmenuPublic getProductNum:aProduct];
		
		if ([obj.item.pProductId isEqualToString:aProduct.pProductId]) {
			 //
			if ([XRmenuPublic getProductNum:aProduct]>0) {
				NSString* count =[NSString stringWithFormat:@"%d",iCount];
				[obj.btnChangeOrder setTitle:count forState:UIControlStateNormal];
				[obj.btnChangeOrder setTitle:count forState:UIControlStateSelected];
				[obj.btnChangeOrder setTitle:count forState:UIControlStateDisabled];
				[obj.btnChangeOrder setTitle:count forState:UIControlStateHighlighted];
			}
			else {
				[obj.btnChangeOrder setHidden:YES];
			}
		}
		
		delIndex++;
	}
}

-(void)cleanOrderd
{
	int delIndex = kTagSortViewBegin;
	DishThumbView* obj = nil;
	while ((obj = (DishThumbView*)[self viewWithTag:delIndex])) {
		[obj.btnChangeOrder setHidden:YES];
		delIndex++;
	}
}

//预设置
-(void)perSetTableView
{
	int hankLeft = 1;
	int hankTop = 31;
	
	int iRowCount = [self.datasource dishThumbWrapperViewRowsInPage];
	int iColCount = [self.datasource dishThumbWrapperViewColumsInPage];
	int iAllCount =[self.datasource dishThumbWrapperDisplayCount];  
	self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, iColCount*thumbWrapperSize.width + hankTop, iRowCount * thumbWrapperSize.height + 33 + hankTop);
	
	self.mNavView.frame = CGRectMake(1, self.frame.size.height-25, self.frame.size.width + thumbMargin.width*(iColCount-1) -hankTop , 30);
	self.mNavView.mPC.numberOfPages = ceil(iAllCount * 1.0 /(iRowCount*iColCount));
	self.mNavView.mPC.currentPage = 0;
	currentPageIndex = 	self.mNavView.mPC.currentPage;
	pageCount = self.mNavView.mPC.numberOfPages;
	
	NSUInteger iRow,iCol,iTagIndex=kTagSortViewBegin;
	for (iRow = 0; iRow < iRowCount; iRow++) { 
		for (iCol = 0; iCol < iColCount; iCol++) { 
			DishThumbView* dishView =[[DishThumbView alloc] init]  ; 
			dishView.frame = CGRectMake(hankLeft + iCol*(thumbWrapperSize.width+thumbMargin.width), 
								  hankTop+iRow*(thumbWrapperSize.height+thumbMargin.height), 
								  thumbWrapperSize.width, thumbWrapperSize.height);
			dishView.tag =iTagIndex;
			dishView.hidden=YES;
			dishView.delegate=self;
			[self addSubview:dishView]; 
			[dishView release];
			iTagIndex++;
		}
	}
	
	[self showPageAtDishId:nil];
}

//外部调用统一接口--空为
-(void)showPageAtDishId:(NSString*)aDishId
{ 
	//aDishId is pEntityId
	int iRowCount = [self.datasource dishThumbWrapperViewRowsInPage];
	int iColCount = [self.datasource dishThumbWrapperViewColumsInPage];
	int iAllCount =[self.datasource dishThumbWrapperDisplayCount];  
	self.mNavView.mPC.numberOfPages = ceil(iAllCount * 1.0 /(iRowCount*iColCount));
	pageCount = self.mNavView.mPC.numberOfPages;
	
	BOOL founded = NO;//是否在当前页找到传递进来的Id
	if (aDishId) {
		
		NSInteger dishInPage = -1;
		
		NSUInteger i, count = [APPSESSION.dishdata count]; 
		 
		for (i = 0; i < count; i++) {
			 Product* obj = [APPSESSION.dishdata objectAtIndex:i];
			 DebugLog(@"楼测试%@---%@",aDishId,obj.pProductId);
			 if ([aDishId isEqualToString:obj.pProductId]) {
			 self.specDishId = aDishId;
			 int iRowCount = [self.datasource dishThumbWrapperViewRowsInPage];
			 int iColCount = [self.datasource dishThumbWrapperViewColumsInPage]; 
			 dishInPage = floor(i / (iRowCount*iColCount)*1.0);
			 break;
		 }
		 }
		if (dishInPage==currentPageIndex) {
			//还在这一页
			founded = YES;
		}
		else {
			currentPageIndex = dishInPage; 
			self.mNavView.mPC.currentPage =	currentPageIndex;
		}

		/*
		//在当前页找
		NSUInteger i, count = [APPSESSION.dishdata count]; 

		for (i = kTagSortViewBegin ; i < kTagSortViewBegin + 12	; i++) {
			ProductTest* test = ((DishThumbView*)[self viewWithTag:i]).item;
			if ([aDishId isEqualToString:test.pEntityId]) {
				founded =YES;
			} 
		}
		if (!founded) { 
			//当前页找不到--就找在第几页
			for (i = 0; i < count; i++) {
				ProductTest* obj = [APPSESSION.dishdata objectAtIndex:i];
				DebugLog(@"楼测试%@---%@",aDishId,obj.pEntityId);
				if ([aDishId isEqualToString:obj.pEntityId]) {
					specDishId = aDishId;
					int iRowCount = [self.datasource dishThumbWrapperViewRowsInPage];
					int iColCount = [self.datasource dishThumbWrapperViewColumsInPage]; 
					currentPageIndex = floor(i / (iRowCount*iColCount)*1.0);
					
					break;
				}
			} 
		}
		*/
		
	}
	else {
		currentPageIndex = 0;
		self.mNavView.mPC.currentPage = 0;
	}
	

	//找不到和有定单更新
	if (!founded || perOrderCount!=[XRmenuPublic getOrderedNum] ) {
		[self reloadData];	
		//[NSThread detachNewThreadSelector:@selector(reloadData) toTarget:self withObject:nil];
	} 
	perOrderCount  =[XRmenuPublic getOrderedNum];
}

-(void)reloadData
{  
	int delIndex = kTagSortViewBegin;
	DishThumbView* obj = nil;
	while ((obj = (DishThumbView*)[self viewWithTag:delIndex])) {
		[obj setHidden:YES];
		obj.sendFlag = NO;
		obj.wrapper.transform= CGAffineTransformMakeScale(1, 1);
		[[obj.wrapper  viewWithTag:kTagFilpView ] removeFromSuperview];
		delIndex++;
	}
 
	//NSAutoreleasePool* pool =[[NSAutoreleasePool alloc] init];
	//清除原来的内容
	
	int iRowCount = [self.datasource dishThumbWrapperViewRowsInPage];
	int iColCount = [self.datasource dishThumbWrapperViewColumsInPage];
	if (currentPageIndex<0) {
		currentPageIndex = 0;
	}
	int iEntityStartIndex =currentPageIndex * (iRowCount * iColCount);
 
	//先创建iRowCount iColCount大小的框
	NSInteger iIndex=0;
	int iRow = 0 ;
	int iCol = 0 ;
	for (iRow=0; iRow < iRowCount; iRow++) {
		for (iCol=0; iCol <iColCount; iCol++) {
			DebugLog(@"%d",[self.datasource dishThumbWrapperDisplayCount]);
			if (iEntityStartIndex>=[self.datasource dishThumbWrapperDisplayCount]) {
				break;//
			}
			//NSAutoreleasePool* pool =[[NSAutoreleasePool alloc] init];
			DishThumbView* ev = [self.datasource dishThumbWrapperView:self viewAtPosition:iEntityStartIndex inPageIndex:iIndex];
			[ev setHidden:NO];
			//[pool release];
			iIndex++;
			iEntityStartIndex++;
		} 
	}
}


 
-(void)dishAlbumNavView:(DishAlbumNavView*)navView perIndex:(NSInteger)perIndex changToIndex:(NSInteger)aIndex
{
	currentPageIndex= aIndex;
	[self reloadData];
	//[NSThread detachNewThreadSelector:@selector(reloadData) toTarget:self withObject:nil];
}

#pragma mark -
#pragma mark 手势事件
- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)recognizer {
	[[self viewWithTag:kTagOperView] removeFromSuperview];
	if (currentPageIndex >=(pageCount - 1)) {//最右边
		return;
	}
 
	self.mNavView.mPC.currentPage += 1;
	currentPageIndex= self.mNavView.mPC.currentPage;
	[self reloadData];
	//[NSThread detachNewThreadSelector:@selector(reloadData) toTarget:self withObject:nil];
	
	//[self transitionWithDirection:kCATransitionFromRight type:kCATransitionMoveIn];
	CATransition *animation = [CATransition animation];
    //animation.delegate = self;
    animation.duration = 0.5f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
	animation.fillMode = kCAFillModeForwards;
	animation.type = kCATransitionPush;
	animation.subtype = kCATransitionFromRight;  ///kCATransitionFromTop;
	[self.layer addAnimation:animation forKey:@"animation"];
	
}

- (void)handleSwipeRight:(UISwipeGestureRecognizer *)recognizer {
	[[self viewWithTag:kTagOperView] removeFromSuperview];
	if (currentPageIndex <=0 ) {//最左边
		return;
	}
 
	
	self.mNavView.mPC.currentPage -= 1;
	currentPageIndex= self.mNavView.mPC.currentPage;
	[self reloadData];
	//[NSThread detachNewThreadSelector:@selector(reloadData) toTarget:self withObject:nil];
	//[self transitionWithDirection:kCATransitionFromLeft type:kCATransitionMoveIn];
	
	CATransition *animation = [CATransition animation];
    //animation.delegate = self;
    animation.duration = 0.5f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
	animation.fillMode = kCAFillModeForwards;
	animation.type = kCATransitionPush;
	animation.subtype = kCATransitionFromLeft;  ///kCATransitionFromTop;
	[self.layer addAnimation:animation forKey:@"animation"];
}

#pragma mark -
#pragma mark Animation 
-(void)transitionWithDirection:(NSString*)aDirection type:(NSString*)aType{
	CATransition *animation = [CATransition animation];
    //animation.delegate = self;
    animation.duration = 0.5f;
    animation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.25f :0.1f :0.25f :1.0f];
	animation.fillMode = kCAFillModeForwards;
	//animation.removedOnCompletion = NO;
	animation.type = aType;
	animation.subtype = aDirection;
	[self.layer addAnimation:animation forKey:@"animation"];
	
 	//[self slideInFrom:kFTAnimationLeft duration:0.2f delegate:nil];
	
}

#pragma mark -
#pragma mark 缩略图 增加 和调整事件
-(void)dishThumbView:(DishThumbView*)aDishThumbView addTapped:(UIButton*)aSender
{  
	[self playAnimationWithThumb:aDishThumbView type:0];
}

-(void)playAnimationWithThumb:(DishThumbView*)aView type:(NSInteger)aType
{ 
	CALayer* layer = [CALayer layer];
	layer.name = kTagAnimationLayerName;
	UIImage* image =aView.dishImageView.image;
	layer.bounds = CGRectMake(0, 0, thumbImageSize.width, thumbImageSize.height);
	layer.position = aView.center;
	layer.contents = (id)image.CGImage; 
	[self.layer addSublayer:layer]; 
	float_t aDuration =0.3f;
    CABasicAnimation *positionAnimation;
	CABasicAnimation *scaleAnimation;  
	CAAnimationGroup *theGroup = [CAAnimationGroup animation]; 
	theGroup.duration = 1.0;
	theGroup.delegate=self; 
	//三个坐标点 屏幕右上角 菜右上角 菜中心位置
	CGPoint screenRT = CGPointMake(720, -5) ;
	CGPoint dishRT =  CGPointMake(aView.frame.origin.x+ aView.frame.size.width-17, aView.frame.origin.y+11);
	CGPoint layerPosition = [[aView.layer valueForKey:@"position"] CGPointValue];
	CGPoint dishC = CGPointMake(layerPosition.x-5, layerPosition.y-15) ;
	
	if (aType==0) {
		 //新增加一道菜
		positionAnimation = [self positionAnimationWithFromVal:dishC
														 toVal: screenRT
													  duration:aDuration]; 
		scaleAnimation = [self scaleAnimationWithFromVal:1.3f toVal:0.01 duration:aDuration]; 
		
	}else if (aType==1) {
		//增加一份
		positionAnimation = [self positionAnimationWithFromVal: dishC
														 toVal: dishRT
													  duration:aDuration]; 
		scaleAnimation = [self scaleAnimationWithFromVal:1.0f toVal:0.01 duration:aDuration]; 
		
		
	}
	else if (aType==2) {
		//减少一份
		positionAnimation = [self positionAnimationWithFromVal: dishRT
														 toVal: dishC
													  duration:aDuration]; 
		scaleAnimation = [self scaleAnimationWithFromVal:0.01f toVal:1.0f duration:aDuration]; 
		
	}
	else if (aType==3) {
		//删除对应份数
		positionAnimation = [self positionAnimationWithFromVal: screenRT
														 toVal: dishC
													  duration:aDuration]; 
		scaleAnimation = [self scaleAnimationWithFromVal:0.01f toVal:1.0f duration:aDuration];
	} 
	else {
		positionAnimation = [self positionAnimationWithFromVal: screenRT
														 toVal: dishC
													  duration:aDuration]; 
		scaleAnimation = [self scaleAnimationWithFromVal:0.01f toVal:1.0f duration:aDuration];
	}

	
	theGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
	theGroup.animations = [NSArray arrayWithObjects:positionAnimation,scaleAnimation, nil];
	theGroup.removedOnCompletion=YES; 
	[layer addAnimation:theGroup forKey:@"zoomAndPosition"]; 
	layer.position = CGPointMake(-1024, -1024);
}

-(CABasicAnimation*)scaleAnimationWithFromVal:(float_t)aFromVal toVal:(float_t)aToVal duration:(float_t)aDuration
{
	CABasicAnimation *scale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
	scale.fromValue = [NSNumber numberWithDouble:aFromVal];
    scale.toValue = [NSNumber numberWithDouble:aToVal];
    scale.duration = aDuration;
    scale.fillMode=kCAFillModeForwards;
    scale.removedOnCompletion=YES; 
	return scale;
}

-(CABasicAnimation*)positionAnimationWithFromVal:(CGPoint)aFromPoint toVal:(CGPoint)aToPoint duration:(float_t)aDuration
{
	CABasicAnimation *scale = [CABasicAnimation animationWithKeyPath:@"position"];
	scale.fromValue = [NSValue valueWithCGPoint:aFromPoint]; 
    scale.toValue = [NSValue valueWithCGPoint:aToPoint]; 
    scale.duration = aDuration;
    scale.fillMode=kCAFillModeForwards;
    scale.removedOnCompletion=YES; 
	return scale;
}

-(void)dishThumbView:(DishThumbView*)aDishThumbView adjustTapped:(UIButton*)aSender
{
	self.currentDishThumbView = aDishThumbView;
	
	if ([self viewWithTag:kTagOperView]) {
		[[self viewWithTag:kTagOperView] removeFromSuperview];
	}
	
	NSDictionary* dic =[APPSESSION.allconfig findAtPath:[NSString stringWithFormat:@"UI Skin/%@/Dish Main View/Dish Album View/DishOperView", APPSESSION.uistyle]];
	DishOperView* operView =[[DishOperView alloc] initWithConfig:dic type:DishOper_Album item:aDishThumbView.item];
	operView.delegate=self;
	operView.center =  CGPointMake(aDishThumbView.frame.origin.x+ aDishThumbView.wrapper.frame.size.width-8,
								   aDishThumbView.frame.origin.y+12);
	operView.tag= kTagOperView;
	[self addSubview:operView]; 
	[operView release];
}

#pragma mark 操作层的委托方法
-(void)dishOperView:(DishOperView *)operView didTappedWith:(DishOperViewOperType)aType
{ 
	
	UIButton* btn = self.currentDishThumbView.btnChangeOrder;
	NSInteger iCount = 0;
	
	switch (aType) {
		case DishOperView_close:
			//关闭
			return;
		case DishOperView_Plus:
		{ 
			//增加
			
			if (![XRmenuPublic  updateProductNum:operView.item Num:[NSNumber numberWithInt:1]]) {
				//return;
			}
			iCount = [XRmenuPublic getProductNum:operView.item] ;
			[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateNormal];
			[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateSelected];
			[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateDisabled];
			[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateHighlighted];
			break;
		}
		case DishOperView_Miuns://减少
		{
#pragma mark todo 只有一份的时候提醒用户
			iCount = [XRmenuPublic getProductNum:operView.item];
			if (iCount==1) {
				[self playAnimationWithThumb:self.currentDishThumbView type:aType];
				[[self viewWithTag:kTagOperView] removeFromSuperview];
				if (![XRmenuPublic clearProduct:operView.item]) {
					//return;
				}
				postN(kMessage_TopBar_orderedChange);
				//通知这个ThumbView修改状态
				[self.currentDishThumbView resumeToOriState];
			}
			else {
				
				if (![XRmenuPublic  updateProductNum:operView.item Num:[NSNumber numberWithInt:-1]]) {
					//return;
				}
				iCount = [XRmenuPublic getProductNum:operView.item];
				[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateNormal];
				[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateSelected];
				[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateDisabled];
				[btn setTitle:[NSString stringWithFormat:@"%d",iCount] forState:UIControlStateHighlighted];
			} 
			break;
		}
		case DishOperView_Delete:
		{
			if (![XRmenuPublic clearProduct:operView.item]) {
				return;
			}
			postN(kMessage_TopBar_orderedChange);
			//删除
			[[self viewWithTag:kTagOperView] removeFromSuperview];
			//通知这个ThumbView修改状态
			[self.currentDishThumbView resumeToOriState];
			
			break;
		}
		case DishOperView_Detail:
		{
			postNWithObj(kMessage_Dish_AlbumToPhoto,self.currentDishThumbView.item.pProductId);
			//详细
			[[self viewWithTag:kTagOperView] removeFromSuperview];
			return;
		}
		default:
			break;
	} 
	if (aType!=DishOperView_Miuns) {
	[self playAnimationWithThumb:self.currentDishThumbView type:aType];		 
	}
}

#pragma mark -
#pragma mark 动画通知
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{

	NSArray* layers =[self.layer sublayers];
	NSUInteger i, count = [layers count];
	for (i = 0; i < count; i++) {
		CALayer * obj = [layers objectAtIndex:i];
		if (obj&&[kTagAnimationLayerName isEqualToString:obj.name]) {
			[obj removeFromSuperlayer];
		}
	}
}

@end
